package com.fast.cms.service.article.impl;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import com.fast.base.dao.daoSuport.JpaDaoSupport;
import com.fast.base.db.sql.AbstractSqlGenerator;
import com.fast.base.db.sql.impl.SqlGeneratorImpl;
import com.fast.base.util.DateUtils;
import com.fast.base.util.data.MathUtils;
import com.fast.base.db.page.PageView;
import com.fast.base.db.page.QueryResult;
import com.fast.cms.constant.CheckStatusEnum;
import com.fast.cms.model.article.Article;
import com.fast.cms.model.article.NoticeInfo;
import com.fast.cms.model.article.SiteMsg;
import com.fast.cms.model.system.Dictionary;
import com.fast.cms.service.article.NoticeInfoService;
import com.fast.cms.web.form.CheckNoticeInfoForm;
import com.fast.cms.web.form.NoticeInfoForm;
import com.fast.user.model.admin.AdminUser;
import com.fast.user.model.admin.Group;

/**
 * 公告服务层实现类
 * @author lushuifa242
 *
 */
@Service("noticeInfoService")
public class NoticeInfoServiceImpl extends JpaDaoSupport implements NoticeInfoService {
	
	/**
	 * 说明:限量查询通知列表 <br>
	 * 编写者:lushuifa
	 * 创建时间:2017年7月13日 下午11:07:16 </pre>
	 * @param 
	 * @return ResponseData 说明
	 */
	@Override
	@Cacheable(value="noticeCache",key="'getNoticeListForLimit'+#noticeTypeId+'_'+#limitSize+'_'+#selectType")
	public List<Map<String, Object>> getNoticeListForLimit(String noticeTypeId, int limitSize, String selectType) {
		StringBuffer sb = new StringBuffer(" where 1=1 ");
		//查出没有回收的数据
		sb.append(" and delete_flag=0 ");
		
		//查出审批通过的数据
		sb.append(" and checkStatus='"+CheckStatusEnum.agree.getCode()+"' ");
		if(StringUtils.isNotBlank(noticeTypeId)){
			sb.append("and noticeTypeId='"+noticeTypeId+"' ");
		}
		
		if(StringUtils.isNotBlank(selectType)){
			if(selectType.equals("newest")){
				sb.append(" order by edit_time desc ");
			}else if(selectType.equals("clickRate")){
				sb.append(" order by readCount desc ");
			}
		}else{
			sb.append(" order by edit_time desc ");
		}
		sb.append(" limit 0,"+limitSize);
		String wheresql = sb.toString();
		String queryFields = "id,uuid,title,noticeType,date_format(edit_time,'%Y-%m-%d')  as editTime ";
		String sql = "select "+queryFields+" from "+AbstractSqlGenerator.getTableName(NoticeInfo.class)+" "+wheresql;
		List<Map<String,Object>> articleList = super.queryForMapList(sql);
		return articleList;
	}

	/**
	 * 获取列表
	 */
	@Override
	public PageView<NoticeInfo> getNoticeInfoList(NoticeInfoForm noticeInfoForm) {
		int page = noticeInfoForm.getPage();//当前页
  		int pagesize = noticeInfoForm.getRows();//每页面显示多少条
  		String deleteFlag = noticeInfoForm.getDeleteFlag();
		StringBuffer sb = new StringBuffer(" where 1=1 ");
		int adminId = Integer.parseInt(noticeInfoForm.getCurUserId());
		boolean isSubUser = this.isSubUserForNotice(adminId);
		
		if(StringUtils.isNotEmpty(deleteFlag)){
			sb.append("and delete_flag="+deleteFlag+" ");
		}else{
			//默认查询未回收的数据
			sb.append("and delete_flag=0 ");
		}
		
		if(StringUtils.isNotEmpty(noticeInfoForm.getTitle())){
			sb.append("and title like '%"+noticeInfoForm.getTitle()+"' ");
		}
		
		if(StringUtils.isNotEmpty(noticeInfoForm.getEditor())){
			sb.append("and editor_name like '%"+noticeInfoForm.getEditor()+"' ");
		}
		
		if(StringUtils.isNotEmpty(noticeInfoForm.getStartPublishTime())&&StringUtils.isNotEmpty(noticeInfoForm.getEndPublishTime())){
			sb.append("and edit_time between '"+noticeInfoForm.getStartPublishTime()+"' and '"+noticeInfoForm.getEndPublishTime()+"' ");
		}
		
		if(!isSubUser){
			if(StringUtils.isNotEmpty(noticeInfoForm.getCheckStatus())){
				sb.append("and checkStatus='"+noticeInfoForm.getCheckStatus()+"' or creater_id="+noticeInfoForm.getCurUserId()+" ");
			}else{
				sb.append("and checkStatus='"+CheckStatusEnum.agree.getCode()+"' or creater_id="+noticeInfoForm.getCurUserId()+" ");
			}
			
		}else{
			if(StringUtils.equals(noticeInfoForm.getSelectType(), "my")){
				sb.append("and creater_id="+noticeInfoForm.getCurUserId()+" ");
			}
			
			if(StringUtils.isNotEmpty(noticeInfoForm.getCheckStatus())){
				sb.append("and checkStatus="+noticeInfoForm.getCheckStatus()+" ");
			}
		}
		
		String ordersql = " order by edit_time desc ";                                                                                                                                                                                                                                          
		QueryResult<NoticeInfo>  queryResult = super.queryForBeanListByPage(NoticeInfo.class,sb.toString(),ordersql,(page-1)*pagesize,pagesize);
		PageView<NoticeInfo> pageView  = new PageView<NoticeInfo>();
	    pageView.setCurrentPage(page);
		pageView.setQueryResult(queryResult);
		
		return pageView;
	}
	
	/**
	 * @Title: isSubUserForNotice 
	 * @Description: 判断某用户是否是
	 * @param curUserId
	 * @developer:LUSHUIFA242
	 * @date 2017年11月7日 下午3:47:27
	 */
	private boolean isSubUserForNotice(int adminId) {
		AdminUser adminUser = super.queryForBeanById(AdminUser.class, adminId);
		Group group = super.queryForBean(Group.class, " where id="+adminUser.getGroupId());
		String groupArray = group.getPermissionArray();
		if(groupArray.contains("PA3B2C1E2E]:审核")||adminUser.getUserName().contains("kaifa")){
			return true;
		}else{
			return false;
		}
	}

	/**
	 * 保存更新
	 * @param noticeInfo
	 * @return
	 */
	@CacheEvict(value="noticeCache",allEntries=true)
	public boolean saveOrUpdateNoticeInfo(NoticeInfo noticeInfo) {
		return this.merge(noticeInfo)!=null;
	}
	
	/**
	 * 审批公告
	 */
	@Override
	@CacheEvict(value="noticeCache",allEntries=true)
	public boolean checkNoticeInfo(CheckNoticeInfoForm checkNoticeForm) {
		int checkStatus = checkNoticeForm.getCheckStatus();
		String checkMsg = checkNoticeForm.getCheckMsg();
		StringBuffer sql = new StringBuffer("");
		sql.append("update "+SqlGeneratorImpl.getTableName(NoticeInfo.class)+" set ");
		sql.append(" checkerId="+checkNoticeForm.getCheckerId()+",");
		sql.append(" checker='"+checkNoticeForm.getChecker()+"',");
		sql.append(" checkStatus="+checkStatus+",");
		sql.append(" check_date='"+DateUtils.getNow()+"',");
		sql.append(" checkMsg='"+checkMsg+"' ");
		sql.append(" where id="+checkNoticeForm.getId()+"");
		boolean actionFlag = super.modifyRow(sql.toString())>0;
		if(actionFlag){
			int id = checkNoticeForm.getId();
			//0为待审核,1为已审核确认,2为审核末通过
			NoticeInfo noticeInfo = super.queryForBeanById(NoticeInfo.class, id);
			//增加信息
			String title = "公告编号【"+noticeInfo.getUuid()+"】"+CheckStatusEnum.getName(checkNoticeForm.getCheckStatus());
			String reciveAdminArr = "["+noticeInfo.getCreaterId()+":"+noticeInfo.getCreater()+"]";
			String msgDetail = "公告标题["+noticeInfo.getTitle()+"] 审批状态为:"+
			CheckStatusEnum.getName(checkNoticeForm.getCheckStatus())+
			" 批阅信息为："+checkNoticeForm.getCheckMsg()+" 审批人为："+
			checkNoticeForm.getChecker()+" 审批时间为："+DateUtils.getNow();
			SiteMsg siteMsg = new SiteMsg(title,"审批信息", reciveAdminArr, msgDetail);
			siteMsg.setUuid(MathUtils.getTheOnlyStr());
			super.merge(siteMsg);
		}
		return actionFlag;
	}
	
	/**
	 * 统计用户的待审批记录
	 * @param adminId
	 * @return
	 */
	public int queryCheckNoticeCount(int adminId){
		boolean isSubUser = isSubUserForNotice(adminId);
		if(isSubUser){
			return  super.count(NoticeInfo.class, " where checkStatus=0 and delete_flag=0");
		}else{
			return 0;
		}
	}

}
